package br.unisinos.pdm.bluetooth;

import br.unisinos.pdm.GameCanvas;
import javax.bluetooth.*;
import javax.microedition.io.*;
import java.io.*;


public class GameClient extends BluetoothConnection implements Runnable{
    
    private ServiceRecord record;
    
    private int initialDiscoverableMode;
    
    public GameClient(GameCanvas gameCanvas, ServiceRecord record){
        super(gameCanvas);
        this.record = record;
    }
    
    public void run() {
        LocalDevice localDevice = null;
        StreamConnection connection = null;
        try{
            
            localDevice = LocalDevice.getLocalDevice();
            initialDiscoverableMode = localDevice.getDiscoverable();
            localDevice.setDiscoverable(DiscoveryAgent.NOT_DISCOVERABLE);
            
            String url = record.getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
            connection = (StreamConnection)Connector.open(url);
            
            execute(connection);
        }catch(IOException ex){
            ex.printStackTrace();
        }finally{
            try{
                if(connection != null) connection.close();              
                localDevice.setDiscoverable(initialDiscoverableMode);
            }catch(IOException ex){}
        }        
    }
    
    public void connect() {
        new Thread(this).start();
    }
}
